/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-08-20
 * Time: 23:29
 */

/**
 * 中序后续遍历构造二叉树:
 */
public class BinaryTreeExercise {
    static class TreeNode{
        int val;
       TreeNode left;
       TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }

    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        posIndex = postorder.length-1;
        return buildTreeChild(postorder,inorder,0,inorder.length-1);
    }

    public int posIndex = 0;
    public TreeNode buildTreeChild(int[] postorder , int[] inorder,int inbegin, int inend){

        if(inbegin > inend){
            return null;
        }

        TreeNode root = new TreeNode(postorder[posIndex]);

        int rootIndex = findVal(inorder,inbegin,inend,postorder[posIndex]);
        posIndex--;//rootInde用完才加加；



        root.right = buildTreeChild(postorder,inorder,rootIndex+1,inend);
        root.left = buildTreeChild(postorder,inorder,inbegin,rootIndex-1);

        return root;
    }

    private int findVal(int[] inorder,int inbegin,int inend,int val){
        for(int i = inbegin; i <= inend; i++) {
            if(val == inorder[i]){
                return i;
            }
        }
        return -1;
    }
}
